import Vue from 'vue';
import VueRouter from 'vue-router';
import { token } from 'utils/localkey';
import store from '../store';

Vue.use(VueRouter);
// 免token可以访问的页面
const whiteRouterNameList = ['Login', 'Register', '404'];

const routes = [
  {
    path: '/',
    redirect: '/index'
  },
  {
    path: '/index',
    name: 'Home',
    component: () =>
      import(/* webpackChunkName: "login" */ '../pages/home/Home'),
    meta: {
      title: 'AI出题'
    }
  },
  {
    path: '/404',
    name: '404',
    component: () => import(/* webpackChunkName: "404" */ '../pages/404/404'),
    meta: {
      title: '404'
    }
  }
];

const createRouter = () =>
  new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
  });
const router = createRouter();
router.beforeEach(async (to, from, next) => {
  next();
});
router.beforeResolve((to, from, next) => {
  /* 路由发生变化修改页面title */
  const title = to.meta.title;
  if (title) {
    store.commit('global/setTitle', title);
  }
  next();
});

// Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465
export function resetRouter() {
  console.log('重置路由对象-----------');
  const newRouter = createRouter();
  router.matcher = newRouter.matcher; // reset router
}

// 处理 vue-route 报错 Uncaught (in promise) undefined
const routerMethods = ['push', 'replace'];
routerMethods.forEach((method) => {
  const originalCall = VueRouter.prototype[method];
  VueRouter.prototype[method] = function (location, onResolve, onReject) {
    if (onResolve || onReject) {
      return originalCall.call(this, location, onResolve, onReject);
    }
    return originalCall.call(this, location).catch((err) => err);
  };
});
export default router;
